package com.fantuan.db.dao;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.springframework.stereotype.Service;

import com.fantuan.db.bean.LoginKey;
import com.fantuan.db.bean.User;

@Service
public class LoginKeyDAO extends BaseDAO{

	public LoginKey getLoginKey(int nid) throws SQLException {

		Connection conn = dataSource.getConnection();

		String sql = "select * from t_login_key where `id`=?";

		LoginKey result = null;
		try {

			Object[] objs = new Object[] { nid };

			result = (LoginKey) this.query(conn, sql, new BeanHandler<LoginKey>(
					LoginKey.class), objs);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(conn);
		}

		return result;
	}
	
	
	
	public LoginKey getLoginKeyByUserID(int userId) throws SQLException {

		Connection conn = dataSource.getConnection();

		String sql = "select * from t_login_key where `userId`=?";

		LoginKey result = null;
		try {

			Object[] objs = new Object[] { userId };

			result = (LoginKey) this.query(conn, sql, new BeanHandler<LoginKey>(
					LoginKey.class), objs);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(conn);
		}

		return result;
	}

	
	
	public LoginKey getLoginKey(String skey) throws SQLException {

		Connection conn = dataSource.getConnection();

		String sql = "select * from t_login_key where `skey`=?";

		LoginKey result = null;
		try {

			Object[] objs = new Object[] { skey };

			result = (LoginKey) this.query(conn, sql, new BeanHandler<LoginKey>(
					LoginKey.class), objs);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(conn);
		}

		return result;
	}
	
	
	
	public long addLoginKey(LoginKey loginKey) throws SQLException {

		String sql = "insert into t_login_key(`userId`,"
				+ "`skey`,`dvalidTime`,`nstate`,"
				+ "`ntype`) values(?,?,?,?,?)";

		long id = -1;
		Connection conn = null;
		try {

			conn = dataSource.getConnection();

			Object[] objs = new Object[] { loginKey.getUserId(),
					loginKey.getSkey(),
					loginKey.getDvalidTime(),
					loginKey.getNstate(),
					loginKey.getNtype()};
			this.update(conn, sql, objs);

			id = this.getLastInsertID(conn);

			DbUtils.close(conn);
		} catch (SQLException e) {
			DbUtils.close(conn);
			e.printStackTrace();
		}

		return id;
	}
	
	
	
	
	public void removeLoginKey(int nid) throws SQLException {

		String sql = "delete from t_login_key where `id`=?";

		long id = -1;
		Connection conn = null;
		try {

			conn = dataSource.getConnection();

			Object[] objs = new Object[] { nid};
			this.update(conn, sql, objs);

			DbUtils.close(conn);
		} catch (SQLException e) {
			DbUtils.close(conn);
			e.printStackTrace();
		}
	}
}
